<?
require_once 'Zend/Search/Lucene.php';

class Search {

    const UID = "uid";

    private $log;
    private $index;

    /**
     * Construct new search
     *
     * @param string $path Path to the index
     */
    public function __construct($path) {

        $this->log =& LoggerManager::getLogger("Search");
        $this->log->debug("Constructing new Searcher");
        
        if(file_exists($path) && is_dir($path)) {
            // open a Zend_Lucene index
            $this->index = Zend_Search_Lucene::open($path);
        } else {
            // create a Zend_Lucene index
            $this->index = Zend_Search_Lucene::create($path);
        }

    }


    public function remove($id) {

        $this->log->debug("Trying to delete lucene record '".$id."'");
        $term = new Zend_Search_Lucene_Index_Term($id, self::UID);
        $docIds = $this->index->termDocs($term);
        foreach ($docIds as $id) {
            $this->log->debug("Delete lucene record '".$id."'");
            $this->index->delete($id);
        }

    }

    public function getIndex() {
        return $this->index;
    }


    public function addDocument($id, $title, $summary, $body, $lang, $url) {

        // Delete old record first!
        $this->remove($id);

        require_once("Zend/Search/Lucene/Document.php");

        $this->log->debug("Adding new document [id={$id}, title={$title}, summary={$summary}, lang={$lang}, url={$url}]");

        // Add new record
        $doc = new Zend_Search_Lucene_Document();

        // Field is not tokenized, but is indexed and stored within the index.
        // Stored fields can be retrived from the index.
        $doc->addField(Zend_Search_Lucene_Field::Keyword(self::UID, $id));
        $doc->addField(Zend_Search_Lucene_Field::Keyword("language", $lang));

        // Field is not tokenized nor indexed, but is stored in the index.
        $doc->addField(Zend_Search_Lucene_Field::UnIndexed("url", $url));
        
        // Field is not tokenized nor indexed, but is stored in the index.
        $doc->addField(Zend_Search_Lucene_Field::Text("summary", $summary));

        // Field is tokenized and indexed, and is stored in the index.
        $doc->addField(Zend_Search_Lucene_Field::Text("title", $title, "utf-8"));

        // Field is tokenized and indexed, but is not stored in the index.
        $doc->addField(Zend_Search_Lucene_Field::UnStored("body", $body, "utf-8"));

        // Add document to the index
        $this->index->addDocument($doc);

    }


    public function optimize() {
        $this->index->optimize();
        $this->index->commit();
    }

}
?>